package coap;

import generic.Request;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.ws4d.coap.Constants;
import org.ws4d.coap.connection.BasicCoapChannelManager;
import org.ws4d.coap.interfaces.CoapChannelManager;
import org.ws4d.coap.interfaces.CoapMessage;
import org.ws4d.coap.interfaces.CoapRequest;
import org.ws4d.coap.interfaces.CoapServer;
import org.ws4d.coap.interfaces.CoapServerChannel;
import org.ws4d.coap.messages.CoapMediaType;
import org.ws4d.coap.messages.CoapResponseCode;

import domainspecific.types.Interval;
import domainspecific.types.MeterReadings;

public class MyCoapServer implements CoapServer {

	private static int PORT = Constants.COAP_DEFAULT_PORT;
	static int counter = 0;

	static
	{
		if(System.getenv().containsKey("READINGS_PORT")){
			PORT = Integer.parseInt(System.getenv().get("READINGS_PORT"));
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Start CoAP Server on port " + PORT);
        MyCoapServer server = new MyCoapServer();

        CoapChannelManager channelManager = BasicCoapChannelManager.getInstance();
        channelManager.createServerListener(server, PORT);

	}


	@Override
	public void handleRequest(CoapServerChannel channel, CoapRequest request) {
		System.out.println("Received message: " + request.toString());
		long numReadings = 0;
		for(String param : request.getUriQuery())
		{
			String[] parts = param.split("=");
			if(parts[0].equals("numReadings"))
			{
				numReadings = Long.parseLong(parts[1]);
				//System.out.println(parts[1]);
			}
		}
		//System.out.println(numReadings);
        CoapMessage response = channel.createResponse(request,
                CoapResponseCode.Content_205);
        response.setContentType(CoapMediaType.xml);
        
        JAXBContext jcontext = null;
		try {
			jcontext = JAXBContext.newInstance(MeterReadings.class);
		} catch (JAXBException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		try {
			Marshaller marshal = jcontext.createMarshaller();
			marshal.marshal(new MeterReadings(numReadings), baos);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        response.setPayload(baos.toByteArray());
        channel.sendMessage(response);

	}


	@Override
	public CoapServer onAccept(CoapRequest request) {
		//System.out.println("Accept connection...");
        return this;
	}


	@Override
	public void separateResponseFailed(CoapServerChannel channel) {
		System.out.println("Seperate response failed.");
	}

}
